package com.xmlt.core.template.tags;


import javax.xml.xpath.XPathExpressionException;


import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.xmlt.core.template.TemplateException;
import com.xmlt.core.template.Utils;

public class TemplateSectionElementFactory {
	public static TemplateSectionElement getTemplateSectionElement(Node n) throws TemplateException {
		TemplateSectionElement element = null;
		if (n.getNodeType() == Node.TEXT_NODE) {
			element =  new TextTag(n.getNodeValue());
		} else if (n.getNodeType() == Node.ELEMENT_NODE) {
			Element el = (Element) n;
			String tagName = el.getTagName();
			String name = el.getAttribute("name");
			if ("tag".equals(tagName)) {
				if ("expression".equals(name) || "element".equals(name)){
					element =  new OutputTag();
				} else if ("condition".equals(name)){
					element =  new IfTag(el);
				} else if ("loop".equals(name)) {
					element = new LoopTag(el);
				} else {
					throw new TemplateException("Unknown tag type: " + name);
				}
			} else if ("br".equals(tagName)) {
				element = new TextTag("<br/>");
			} else {
				// ignore
			}
		}
		if (element != null) {
			setParams(element, n);
		}
		return element;
	}
	
	private static void setParams(TemplateSectionElement el, Node n) throws TemplateException {
		NodeList params = null;
		try {
			params = Utils.evaluateXPath(n, "parameter");
		} catch (XPathExpressionException e) {
			// 
		}
		if (params != null) {
			for (int i = 0; i < params.getLength(); i++) {
				Element pNode = (Element) params.item(i);
				String name = pNode.getAttribute("name");
				el.setParameter(name, pNode);
			}
		}
	}
}
